<?php

declare(strict_types=1);

namespace WanZ\App\User\Action;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use WanZ\App\User\Logic\UserLogic;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;

/**
 * 绑定用户手机
 * @Controller
 */
class BindPhone extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var UserLogic
     */
    private $userLogic;
        
    /**
     * @RequestMapping(path="/user/info/bind", methods="GET")
     * @return array 返回数组
     */
    public function handle(): array
    {       
        ## 参数验证
        $this->validated($this->request->all());

        ## 请求参数
        $userType = (int) $this->request->input('u_type');
        $phone = (string) $this->request->input('phone');
        $code = (string) $this->request->input('code');
        $userId = (int) $this->request->input('u_id');
        $type = (string) $this->request->input('type');

		$result = $this->userLogic->bind($phone, $code, $userId, $type);
        if (! $result) {
            throw new CommonException(ErrorCode::SERVER_ERROR, '绑定手机号失败');
        }

		return [];
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
            'u_type' => 'required|in:1|bail',
            'phone' => 'required|size:11|phone|bail',
            'code' => 'required|string|size:6|bail',
            'u_id' => 'required|integer|min:1|bail',
            'type' => 'required|string|in:wx,ali|bail',
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
            'u_type.required' => '用户类型 必填',
            'u_type.in' => '用户类型 非法 值必须为：1',
            'phone.required' => '手机号码 必填',
            'phone.size' => '手机号码 字符串长度为固定值：11',
            'phone.phone' => '手机号码 格式不正确',
            'code.required' => '验证码 必填',
            'code.string' => '验证码 必需为字符串',
            'code.size' => '验证码 字符串长度为固定值：6',
            'u_id.required' => '用户ID 必填',
            'u_id.integer' => '用户ID 必需为整数',
            'u_id.min' => '用户ID 值必须大于1',
            'type.required' => '登录类型 必填',
            'type.string' => '登录类型 必需为字符串',
            'type.in' => '登录类型 非法 值必须在列表内：[wx,ali]',
        ];
    }
}